﻿(function(ko) {

    function setupWidgetBinding(widgetName) {
        ko.bindingHandlers[widgetName] = {
            init: function(element, valueAccessor, allBindingsAccessor) {
                var options = valueAccessor(),
                    allBindings = allBindingsAccessor();
                $(element)[widgetName](options);

                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    $(element)[widgetName]('destroy');
                });
            }
        };
    }

    setupWidgetBinding('datepicker');

    ko.bindingHandlers.select2 = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            var optionsCreator = valueAccessor(),
                allBindings = allBindingsAccessor();

            var init = ko.utils.unwrapObservable(allBindings.initText);
            var val = ko.utils.unwrapObservable(allBindings.value);
            var options = optionsCreator({ id: val, text: init });

            $(element).select2(options);
            
            ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                $(element).select2('destroy');
            });
        },
        update: function(element) {
            //$(element).trigger('change');
        }
    };

})(window.ko);